<?php

class PerusahaanController extends Controller
{
    public $layout='//layouts/column2';
    public $defaultAction='admin';

    protected function getIndexList($model) {
    $indexList = array(
        array(
                'name' => 'nama_perusahaan',
                'value' => '($data->nama_perusahaan) ? $data->nama_perusahaan : "-"',
        ),array(
            'name' => 'jenis_usaha',
            'value' => '($data->jenis_usaha) ? $data->jenis_usaha : "-"',
        ),array(
                'htmlOptions' => array('class'=>'button-column'),
                'class'=>'booster.widgets.TbButtonColumn',
                'template'=> '{view} {delete}',
                'buttons'=>array(
                    'delete'=>array(
                        'visible'=>'Yii::app()->user->isAdmin()',
                    ),
                )
            ),
    );
    return $indexList;
    }

    protected function getViewList($model) {
    $viewList = array(
        array(
                'name' => 'nama_perusahaan',
                'value' => ($model->nama_perusahaan) ? $model->nama_perusahaan : "-",
        ),array(
                'name' => 'pengurus',
                'value' => ($model->pengurus) ? $model->pengurus : "-",
        ),array(
                'name' => 'bentuk_badan_usaha',
                'value' => ($model->bentuk_badan_usaha) ? $model->bentuk_badan_usaha : "-",
        ),array(
                'name' => 'jenis_usaha',
                'value' => ($model->jenis_usaha) ? $model->jenis_usaha : "-",
        ),array(
                'name' => 'jenis_produk',
                'value' => ($model->jenis_produk) ? $model->jenis_produk : "-",
        ),array(
                'name' => 'alamat',
                'value' => ($model->alamat) ? $model->alamat : "-",
        ),array(
                'name' => 'kota_id',
                'value' => ($model->kota_id) ? $model->kota_id : "-",
        ),array(
                'name' => 'telepon',
                'value' => ($model->telepon) ? $model->telepon : "-",
        ),array(
                'name' => 'fax',
                'value' => ($model->fax) ? $model->fax : "-",
        ),array(
                'name' => 'mobile_phone',
                'value' => ($model->mobile_phone) ? $model->mobile_phone : "-",
        ),array(
                'name' => 'kode_pos',
                'value' => ($model->kode_pos) ? $model->kode_pos : "-",
        ),array(
                'name' => 'email',
                'value' => ($model->email) ? $model->email : "-",
        ),array(
                'name' => 'website',
                'value' => ($model->website) ? $model->website : "-",
        ),array(
                'name' => 'kantor_cabang',
                'value' => ($model->kantor_cabang) ? $model->kantor_cabang : "-",
        ),array(
                'name' => 'upload_dokumen',
                'value' => ($model->upload_dokumen) ? $model->upload_dokumen : "-",
        ));
        return $viewList;
    }
    
    public function actionIndex()
    {
        $c = new CDbCriteria;
        $c->with = array(
                        'provinsi'=>array(
                            'select'=>'nama,koordinat'
                        )
            );
        $c->condition = 'provinsi.koordinat!=:koordinat';
        $c->addCondition('t.provinsi_id!=:prov');
        $c->group = 't.provinsi_id';
        $c->params = array(':koordinat'=>'null',':prov'=>'null');
        $data = Izin::model()->findAll($c);
        $this->render('index', array(
            'data' => $data,
        ));
    }
    
    public function actionOperator()
    {
        $model = new Perusahaan('search');
        $model->unsetAttributes();
        if (isset($_GET['Perusahaan']))
            $model->attributes = $_GET['Perusahaan'];
        $this->render('admin', array(
            'model' => $model,
        ));
    }

    /**
    * Manages all models.
    */
    public function actionAdmin()
    {
        $model = new Perusahaan('search');
        $model->unsetAttributes();
        if (isset($_GET['Perusahaan']))
            $model->attributes = $_GET['Perusahaan'];
        $this->render('admin', array(
            'model' => $model,
        ));
    }

    public function actionCategory($id=null)
    {
        switch ($id) {
            case 1:
                $jenisUsaha = 'Pengolahan MB';
                $jenisUsahaAlias = 'Pengolahan Minyak Bumi';
                break;
            case 2:
                $jenisUsaha = 'Pengolahan GB';
                $jenisUsahaAlias = 'Pengolahan Gas Bumi';
                break;
            case 3:
                $jenisUsaha = 'Pengolahan HO';
                $jenisUsahaAlias = 'Pengolahan Hasil Olahan';
                break;
            default:
                $jenisUsaha = '';
                $jenisUsahaAlias = 'Semua Data Perusahaan';
                break;
        }
        $model = new Perusahaan('search');
        $model->unsetAttributes();
        if (isset($_GET['Perusahaan']))
            $model->attributes = $_GET['Perusahaan'];
        if(!empty($id))
           $model->jenis_usaha = $jenisUsaha;
        $this->render('category', array(
            'model' => $model,
            'jenisUsahaAlias' => $jenisUsahaAlias,
        ));
    }
    
    /**
    * Displays a particular model.
    * @param integer $id the ID of the model to be displayed
    */
    
    public function actionView($id)
    {
        $this->render('view',array(
            'model'=>$this->loadModel($id),
        ));
    }
    
    public function actionCreate()
    {
        $model=new Perusahaan;
        $izin=new Izin;
        if(isset($_POST['Perusahaan'],$_POST['Izin']))
        {
            $model->attributes=$_POST['Perusahaan'];
            $izin->attributes=$_POST['Izin'];
            //Set Path By Jenis Usaha ex: 1 Pengolahan MB/2 Pengolahan GB etc.
            if($model->jenis_usaha == 'Pengolahan MB')
                $dirName = '1 Pengolahan MB';
            if($model->jenis_usaha == 'Pengolahan GB')
                $dirName = '2 Pengolahan GB';
            if($model->jenis_usaha == 'Pengolahan HO')
                $dirName = '3 Pengolahan HO';
            
            $badanUsaha = $model->bentuk_badan_usaha;
            $nama = $model->nama_perusahaan;
            
            if($model->save())
            {
                if($model->id===null)
                    throw new CHttpExeption('ID Perusahaan is Empty.');
                $id  = $model->id;
                
                $rootDir = '/uploaded_files/attachment/'.$dirName.'/'.$id.' '.$badanUsaha.' '.$nama;
                $path = YiiBase::getPathOfAlias('webroot').$rootDir;
                $this->createDir($path);
                $izin->perusahaan_id = $id;
                //Save Izin
                if($izin->save())
                {
                    if($izin->id===null)
                        throw new CHttpException('Izin ID is empty');
                    $izinID = $izin->id;
                    $admin = CHtml::listData(Administrasi::model()->findAll(array('select'=>'id,nama')),'id','nama');
                    if(!empty($admin))
                    {
                        foreach ($admin as $k => $v) {
                            $checklist = new ChecklistAdmin;
                            $checklist->izin_id = $izinID;
                            $checklist->administrasi_id = $k;
                            if($checklist->save())
                            {
                                $adminDetail = new AdministrasiDetail;
                                $adminDetail->checklist_admin_id = $checklist->id;
                                $adminDetail->save();
                            }
                        }
                    }
                    $evaluasi = CHtml::listData(Evaluasi::model()->findAll(array('select'=>'id,nama')),'id','nama');
                    if(!empty($evaluasi))
                    {
                        foreach ($evaluasi as $k => $v) {
                            $checklist = new ChecklistEvaluasi;
                            $checklist->izin_id = $izinID;
                            $checklist->evaluasi_id = $k;
                            $checklist->save();
                        }
                    }
                    $lain = CHtml::listData(LainLain::model()->findAll(array('select'=>'id,nama')),'id','nama');
                    if(!empty($evaluasi))
                    {
                        foreach ($lain as $k => $v) {
                            $checklist = new ChecklistLain;
                            $checklist->izin_id = $izinID;
                            $checklist->lain_lain_id = $k;
                            $checklist->save();
                        }
                    }
                    $perizinan = CHtml::listData(Perizinan::model()->findAll(array('select'=>'id,nama')),'id','nama');
                    if($perizinan!==null)
                    {
                        foreach ($perizinan as $k => $v) {
                            $checklist = new ChecklistPerizinan;
                            $checklist->izin_id = $izinID;
                            $checklist->perizinan_id = $k;
                            $checklist->save();
                        }
                    }
                    $surat = CHtml::listData(SuratTerkait::model()->findAll(array('select'=>'id,nama')),'id','nama');
                   if(!empty($surat))
                    {
                        foreach ($surat as $k => $v) {
                            $checklist = new ChecklistSurat;
                            $checklist->izin_id = $izinID;
                            $checklist->surat_terkait_id = $k;
                            $checklist->save();
                        }
                    }
                    $teknis= CHtml::listData(Teknis::model()->findAll(array('select'=>'id,nama')),'id','nama');
                    if(!empty($teknis))
                    {
                        foreach ($teknis as $k => $v) {
                            $checklist = new ChecklistTeknis;
                            $checklist->izin_id = $izinID;
                            $checklist->teknis_id = $k;
                            $checklist->save();
                        }
                    }
                    $this->redirect(array('izin/'.$izinID));
                }
            }
        }
        $data['prov'] = CHtml::listData(Provinsi::model()->findAll(array('select' => 'id, nama')), 'id', 'nama');
        $this->render('create',array(
            'model'=>$model,
            'izin'=>$izin,
            'data'=>$data,
        ));
    }

    public function actionGetKabupaten($id) {
        $this->layout = false;
        if (Yii::app()->request->isAjaxRequest) {
            $kab = Kabupaten::model()->findAll(array('select' => 'id, nama', 'condition' => "t.provinsi_id = $id"));
            $data = array();
            foreach ($kab as $d) {
                $data[] = array('id' => $d->id, 'text' => $d->nama);
            }
            echo CJSON::encode($data);
        }
    }

    public function actionUpdate($id)
    {
        $model=$this->loadModel($id);
        $izin = Izin::model()->findByAttributes(array('perusahaan_id'=>$model->id));
        $this->performAjaxValidation($model);
        if(isset($_POST['Perusahaan'],$_POST['Izin']))
        {
            $model->attributes=$_POST['Perusahaan'];
            $izin->attributes=$_POST['Izin'];
            $izinID = $izin->id;
        if($model->save())
            $izin->save();
            $this->redirect(array('izin/'.$izinID));
        }
        $data = array();
        $data['prov'] = CHtml::listData(Provinsi::model()->findAll(array('select' => 'id, nama')), 'id', 'nama');
        $kab = Kabupaten::model()->findAll(array('select' => 'id, nama', 'condition' => "provinsi_id = " . $izin->provinsi_id));
        if ($kab) {
            foreach ($kab as $d) {
                $data['oldk'][] = array('id' => $d->id, 'text' => $d->nama);
            }
        }
        $this->render('update',array(
            'model'=>$model,
            'izin'=>$izin,
            'data'=>$data,
        ));
    }
    
/*  Action Create Has Many                */    
/*    public function actionCreate()
    {
        $model=new Perusahaan;
        if(isset($_POST['Perusahaan']))
        {
            $model->attributes=$_POST['Perusahaan'];
            //Set Path By Jenis Usaha ex: 1 Pengolahan MB/2 Pengolahan GB etc.
            if($model->jenis_usaha == 'Pengolahan MB')
                $dirName = '1 Pengolahan MB';
            if($model->jenis_usaha == 'Pengolahan GB')
                $dirName = '2 Pengolahan GB';
            if($model->jenis_usaha == 'Pengolahan HO')
                $dirName = '3 Pengolahan HO';
            
            $badanUsaha = $model->bentuk_badan_usaha;
            $nama = $model->nama_perusahaan;
            if($model->save())
            {
                if($model->id===null)
                    throw new CHttpExeption('ID Perusahaan is Empty.');
                $id  = $model->id;
                $fileName = $id.'-'.$badanUsaha.' '.$nama.'.pdf';
                
                //Create Dir
                    $path = YiiBase::getPathOfAlias('webroot').'/uploaded_files/attachment/'.$dirName.'/'.$id.' '.$badanUsaha.' '.$nama;
                    $this->createDir($path);
                
                    $admin = CHtml::listData(Administrasi::model()->findAll(array('select'=>'id,nama')),'id','nama');
                    if(!empty($admin))
                    {
                        foreach ($admin as $k => $v) {
                            $checklist = new ChecklistAdmin;
                            $checklist->perusahaan_id = $id;
                            $checklist->administrasi_id = $k;
                            if($checklist->save())
                            {
                                $adminDetail = new AdministrasiDetail;
                                $adminDetail->checklist_admin_id = $checklist->id;
                                $adminDetail->save();
                            }
                        }
                    }
                    $evaluasi = CHtml::listData(Evaluasi::model()->findAll(array('select'=>'id,nama')),'id','nama');
                    if(!empty($evaluasi))
                    {
                        foreach ($evaluasi as $k => $v) {
                            $checklist = new ChecklistEvaluasi;
                            $checklist->perusahaan_id = $id;
                            $checklist->evaluasi_id = $k;
                            $checklist->save();
                        }
                    }
                    $perizinan = CHtml::listData(Perizinan::model()->findAll(array('select'=>'id,nama')),'id','nama');
                    if($perizinan!==null)
                    {
                        foreach ($perizinan as $k => $v) {
                            $checklist = new ChecklistPerizinan;
                            $checklist->perusahaan_id = $id;
                            $checklist->perizinan_id = $k;
                            $checklist->save();
                        }
                    }
                    $surat = CHtml::listData(SuratTerkait::model()->findAll(array('select'=>'id,nama')),'id','nama');
                   if(!empty($surat))
                    {
                        foreach ($surat as $k => $v) {
                            $checklist = new ChecklistSurat;
                            $checklist->perusahaan_id = $id;
                            $checklist->surat_terkait_id = $k;
                            $checklist->save();
                        }
                    }
                    $teknis= CHtml::listData(Teknis::model()->findAll(array('select'=>'id,nama')),'id','nama');
                    if(!empty($teknis))
                    {
                        foreach ($teknis as $k => $v) {
                            $checklist = new ChecklistTeknis;
                            $checklist->perusahaan_id = $id;
                            $checklist->teknis_id = $k;
                            $checklist->save();
                        }
                    }
                    $this->redirect(array('perusahaan/admin'));
            }
        }
        $this->render('create',array(
            'model'=>$model,
        ));
    }*/

/* Action Create Has One */    

/*    public function actionCreate()
    {
        $model=new Perusahaan;
        $izin=new Izin;
        if(isset($_POST['Perusahaan'],$_POST['Izin']))
        {
            $model->attributes=$_POST['Perusahaan'];
            $izin->attributes=$_POST['Izin'];
            //Set Path By Jenis Usaha ex: 1 Pengolahan MB/2 Pengolahan GB etc.
            if($model->jenis_usaha == 'Pengolahan MB')
                $dirName = '1 Pengolahan MB';
            if($model->jenis_usaha == 'Pengolahan GB')
                $dirName = '2 Pengolahan GB';
            if($model->jenis_usaha == 'Pengolahan HO')
                $dirName = '3 Pengolahan HO';
            
            $badanUsaha = $model->bentuk_badan_usaha;
            $nama = $model->nama_perusahaan;
            
            if($model->save())
            {
                if($model->id===null)
                    throw new CHttpExeption('ID Perusahaan is Empty.');
                $id  = $model->id;
                
                $fileName = $id.'-'.$badanUsaha.' '.$nama.'.pdf';
                if(!empty($izin->tanggal_terbit))
                {
                    $tanggalTerbit = str_replace('-', '', $izin->tanggal_terbit);
                    $fileName = $id.'-'.$tanggalTerbit.'-'.$badanUsaha.' '.$nama.'.pdf';
                }
                
                $file = CUploadedFile::getInstance($izin, 'upload_dokumen');
                if (is_object($file) && get_class($file) === 'CUploadedFile')
                    $izin->upload_dokumen = $file;
                $rootDir = '/uploaded_files/attachment/'.$dirName.'/'.$id.' '.$badanUsaha.' '.$nama;
                $path = YiiBase::getPathOfAlias('webroot').$rootDir;
                if (is_object($izin->upload_dokumen)) {
                    $this->createDir($path);
                    $izin->upload_dokumen->saveAs($path.'/3 Izin/'.$fileName);
                }
                $izin->perusahaan_id = $id;
                $izin->upload_dokumen = $fileName;
                $izin->path_dokumen = $rootDir;
                //Save Izin
                if($izin->save())
                {
                    if($izin->id===null)
                        throw new CHttpException('Izin ID is empty');
                    
                        $admin = CHtml::listData(Administrasi::model()->findAll(array('select'=>'id,nama')),'id','nama');
                    if(!empty($admin))
                    {
                        foreach ($admin as $k => $v) {
                            $checklist = new ChecklistAdmin;
                            $checklist->izin_id = $izin->id;
                            $checklist->administrasi_id = $k;
                            if($checklist->save())
                            {
                                $adminDetail = new AdministrasiDetail;
                                $adminDetail->checklist_admin_id = $checklist->id;
                                $adminDetail->save();
                            }
                        }
                    }
                    $evaluasi = CHtml::listData(Evaluasi::model()->findAll(array('select'=>'id,nama')),'id','nama');
                    if(!empty($evaluasi))
                    {
                        foreach ($evaluasi as $k => $v) {
                            $checklist = new ChecklistEvaluasi;
                            $checklist->izin_id = $izin->id;
                            $checklist->evaluasi_id = $k;
                            $checklist->save();
                        }
                    }
                    $perizinan = CHtml::listData(Perizinan::model()->findAll(array('select'=>'id,nama')),'id','nama');
                    if($perizinan!==null)
                    {
                        foreach ($perizinan as $k => $v) {
                            $checklist = new ChecklistPerizinan;
                            $checklist->izin_id = $izin->id;
                            $checklist->perizinan_id = $k;
                            $checklist->status_kelengkapan = 'Ada';
                            $checklist->upload_dokumen = $fileName;
                            $checklist->path_dokumen = $rootDir;
                            $checklist->save();
                        }
                    }
                    $surat = CHtml::listData(SuratTerkait::model()->findAll(array('select'=>'id,nama')),'id','nama');
                   if(!empty($surat))
                    {
                        foreach ($surat as $k => $v) {
                            $checklist = new ChecklistSurat;
                            $checklist->izin_id = $izin->id;
                            $checklist->surat_terkait_id = $k;
                            $checklist->save();
                        }
                    }
                    $teknis= CHtml::listData(Teknis::model()->findAll(array('select'=>'id,nama')),'id','nama');
                    if(!empty($teknis))
                    {
                        foreach ($teknis as $k => $v) {
                            $checklist = new ChecklistTeknis;
                            $checklist->izin_id = $izin->id;
                            $checklist->teknis_id = $k;
                            $checklist->save();
                        }
                    }
                    $this->redirect(array('izin/admin'));
                }
            }
        }
        $this->render('create',array(
            'model'=>$model,
            'izin'=>$izin,
        ));
    }*/

    public function actionRead($id) {
        $model = $this->loadModel($id);
        $this->render('read', array(
            'model' => $model,
        ));
    }

    public function actionDetail($id) {
        $model=new CActiveDataProvider('ChecklistAdmin', array(
            'criteria'=>array(
                'condition'=>'perusahaan_id='.$id
                )
            )
        );
        $perusahaan = Perusahaan::model()->findByPk($id);
        $this->render('detail', array(
            'model' => $model,
            'perusahaan'=>$perusahaan
        ));
    }

    public function actionDelete($id)
    {
    if(Yii::app()->request->isPostRequest)
    {
    $this->loadModel($id)->delete();
    if(!isset($_GET['ajax']))
    $this->redirect(isset($_POST['returnUrl']) ? $_POST['returnUrl'] : array('admin'));
    }
    else
    throw new CHttpException(400,'Invalid request. Please do not repeat this request again.');
    }

    public function loadModel($id)
    {
        $model=Perusahaan::model()->findByPk($id);
        if($model===null)
            throw new CHttpException(404,'The requested page does not exist.');
        return $model;
    }
    
    protected function performAjaxValidation($model)
    {
        if(isset($_POST['ajax']) && $_POST['ajax']==='perusahaan-form')
        {
            echo CActiveForm::validate($model);
            Yii::app()->end();
        }
    }
    
    
    protected function createDir($path) {
            $klasifikasi = array('',
                'Persyaratan Administratif',
                'Persyaratan Teknis',
                'Izin',
                'Surat Terkait',
                'Evaluasi',
                'Lain-lain'
            );
                    $old=  umask(0);
                    mkdir($path, 0777, true);
                    umask($old);
                    for($i=1;$i<=6;$i++)
                    {
                        //create dir klasifikasi
                        $old2 = umask(0);
                        mkdir($path.'/'.$i.' '.$klasifikasi[$i],0777,true);
                        umask($old2);
                    }
    }
    
    public function actionGenerate($id=null)
    {
//        $checklist=new Checklist;
//                    $checklist->attributes = $checklist;
//                    $checklist->perusahaan_id = $id;
//                    if($checklist->save())
//                    {
                        $data= CHtml::listData(Teknis::model()->findAll(array('select'=>'id,nama')),'id','nama');
                            foreach($data as $k => $v){
                                    $checklistDetail=new ChecklistTeknis;
                                    $checklistDetail->izin_id = $id;
                                    //$checklistDetail->status = (in_array($k,$_POST['ChecklistDetail']['status'])) ? 'Ada':'Tidak';
                                    $checklistDetail->teknis_id = $k;
                                    $checklistDetail->save();
                            }
//                            $administrasi = CHtml::listData(Administrasi::model()->findAll(array('select'=>'id,nama')),'id','nama');
//                            foreach ($administrasi as $keyAdm => $vAdm) {
//                                    $checklistAdm=new ChecklistAdministrasi;
////                                    $checklistDetail=new ChecklistDetail;
//                                    $checklistAdm->checklist_id = $checklist->id;
//                                    $chrecklistAdm->administrasi_id = $keyAdm;
//                                    $checklistAdm->save();
//                            }
//                            $this->redirect(array($this->defaultAction));
                            echo 'Sukses!';
//                    }
    }
}
